<template>
  <div>
    <el-upload
      v-loading="loading"
      action="#"
      list-type="picture-card"
      :on-remove="handleRemove"
      :file-list="fileList"
      :on-change="onChange"
      :http-request="onRequest"
      :on-preview="onPreview"
      :before-upload="beforeUpload"
      :limit="1"
      :class="fileList.length === 1 ? 'hideAdd' : '' "
      class="custom-upload"
    >
      <el-dialog :visible.sync="dialogVisible">
        <img style="width: 100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <i class="el-icon-plus" />
      <!-- <el-button size="small" type="primary">点击上传</el-button> -->
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: ' AKIDX0MUQ7aorhGYo13oKacQzJPH6wd4E9tQ',
  SecretKey: ' LPEyXp4CHAWfcLr8C6mESSPDtJWVH1c0'
})
console.log(cos)
export default {
  name: 'UploadImg',
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: '',
      loading: false
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    onChange(file, fileList) {
      this.fileList = fileList
      console.log('上传图片')
    },
    onRequest(file) { // 覆盖默认的请求，自定义请求
      this.loading = true
      cos.putObject({
        Bucket: 'rxj-1315602260', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: file, // 上传文件对象
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        // console.log(err || data)
        if (!err && data.statusCode === 200) {
          this.$emit('onSuccess', 'https://' + data.Location)
        }
        this.loading = false
      })
    },
    onPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp']
      if (!types.includes(file.type)) {
        // 检查上传的图片 格式
        this.$message.warning('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      //  检查图片的大小
      const maxSize = 5 * 1024 * 1024
      if (maxSize < file.size) {
        this.$message.warning('图片大小最大不能超过5M')
        return false
      }
      return true
    }

  }

}
</script>

<style lang="scss">
.hideAdd .el-upload--picture-card {
  display: none;
}
.custom-upload {
  width: 148px;
  height: 148px;
  overflow: hidden;
}

</style>
